package com.only.common.enums;



import com.only.common.exception.BizExceptionFactory;

import java.util.Optional;

/**
 * @author only
 * @date 2023/6/14
 * @description
 */
public interface GeneralCodeEnum extends CodeBaseEnum {
    static <T extends GeneralCodeEnum> Optional<T> create(String code, Class<T> enumType) {
        for (T value: enumType.getEnumConstants()) {
            if (value.getCode().equals(code)) {
                return Optional.of(value);
            }

            if (value.toString().equals(code)) {
                return Optional.of(value);
            }
        }

        return Optional.empty();
    }

    static <T extends GeneralCodeEnum> T createWithException(String code, Class<T> enumType) {
        return create(code, enumType)
            .orElseThrow(() -> BizExceptionFactory.invalidEnumValue(code, enumType.getName()));
    }

    public default GeneralEnumVO toEnumGeneralVO() {
        return new GeneralEnumVO(this);
    }

    public static <T extends GeneralCodeEnum> GeneralEnumVO createEnumVO(String code, Class<T> enumType) {
        return create(code, enumType).map(GeneralCodeEnum::toEnumGeneralVO).orElse(null);
    }

    public static GeneralEnumVO getEnumGeneralVO(GeneralCodeEnum elem) {
        if (elem == null) {
            return null;
        }
        return elem.toEnumGeneralVO();
    }

    public static String getEnumCode(GeneralCodeEnum elem) {
        if (elem == null) {
            return null;
        }
        return elem.getCode();
    }

    public static String getEnumComment(GeneralCodeEnum elem) {
        if (elem == null) {
            return null;
        }
        return elem.getComment();
    }
}
